<template>
  <div class="container">
    <div class="card-container">
      <el-card v-for="room in getroomlist" :key="room.id" class="room-card" style="margin-bottom: 20px;">
        <template #header>
          <div class="card-header">
            <span>{{ room.roomname }}</span>
          </div>
        </template>
        <div class="card-body">
          <p>负责人：{{room.username}}</p>
          <p>容纳人数: {{ room.capacity }}</p>
          <p>位置：{{room.location}}</p>
          <p>负责人电话：{{room.phone}}</p>

        </div>
        <template #footer>
          <div>Footer content for {{ room.title }}</div>
        </template>
      </el-card>
    </div>
    <FullCalendar ref="fullCalendar" :options="calendarOptions" class="fullcalendar" />
  </div>
</template>

<script setup>
import FullCalendar from '@fullcalendar/vue3';
import resourceTimelinePlugin from '@fullcalendar/resource-timeline';
import { ref, onMounted, computed } from 'vue';
import { roomBookUsage } from "@/api/book";

import {getroomStatByTime, roomlist} from "@/api/room";

const getroomlist = ref([]);
const statlist = ref([]);
const eventList = ref([]);


function getRoomBookings(roomId) {
  const room = statlist.value.find(r => r.id === roomId);
  return room ? room.bookings.map(booking => `${booking.startTime} - ${booking.endTime}`).join(', ') : '无预定';
}

const calendarOptions = ref({
  plugins: [resourceTimelinePlugin],
  initialView: 'resourceTimeline',
  resources: computed(() => statlist.value),
  events: computed(() => eventList.value),
  locale: 'zh-cn',
  eventClick: handleEventClick,
  // datesSet: handleDatesSet,
  slotMinTime: '09:00:00',
  slotMaxTime: '21:00:00',
});

onMounted(async () => {
  await fetchRoomData();
  updateEventList();
});
async function fetchRoomData() {
  try {
    const roomResponse = await roomlist(); // 假设roomlist是个async函数
    getroomlist.value = roomResponse.data;

    const response = await roomBookUsage();
    await updateRoomData(response.data);
  } catch (error) {
    console.error("Error fetching room data:", error);
    alert("无法加载房间数据，请稍后再试。");
  }
}

function updateRoomData(data) {
  const roomMap = {};

  // 将数据整理到 roomMap 中，按房间名分组
  data.forEach(item => {
    if (!roomMap[item.roomname]) {
      roomMap[item.roomname] = [];
    }
    roomMap[item.roomname].push({
      startTime: item.startTime,
      endTime: item.endTime
    });
  });

  // 将整理好的数据转换为 statlist
  statlist.value = Object.keys(roomMap).map((roomName, index) => ({
    id: index.toString(),
    title: roomName,
    bookings: roomMap[roomName] // 将预定信息放入 bookings
  }));

  updateEventList(); // 更新事件列表
}

async function updateEventList() {
  const bookings = statlist.value.flatMap(room =>
      room.bookings.map(booking => ({
        resourceId: room.id,  // 确保 resourceId 对应房间的 id
        start: new Date(booking.startTime).toISOString(),
        end: new Date(booking.endTime).toISOString(),
        title: room.title, // 作为事件的标题
      }))
  );

  console.log('Bookings:', bookings); // 调试信息
  eventList.value = bookings;
}

function handleEventClick(arg) {
  alert('Event clicked: ' + arg.event.title);
}
</script>

<style scoped>
/* Style your components */
.container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 100vh;
}

.card-container {
  width: 300px;
  padding: 20px;
  border-right: 1px solid #ddd;
  overflow-y: auto;
}

.room-card {
  width: 100%;
}

.fullcalendar {
  flex: 1;
  margin: 0;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>